package sort;

import java.util.Arrays;

/**
 * 快速排序
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {8, 9, 0, 7, 2, 3, 5, 4, 6, 1};
        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    /**
     * 取最中间的作为基准值
     * @param arr
     */
    public static void quickSort(int[] arr, int left, int right){
        int low = left;
        int high = right;
        int pivot = arr[low + ( high - low) /2];
        while(low <= high){
            // 左边比基准值小，右边比基准值大
            while(arr[low] <pivot){
                low++;
            }
            while(arr[high] > pivot){
                high--;
            }
            if(low >= high){
                break;
            }
            int temp = arr[low];
            arr[low] = arr[high];
            arr[high] = temp;
            //交换之后，如果发现指针所指的值和基准相等，则继续移动
            if(arr[low] == pivot){
                high--;
            }
            if(arr[high] == pivot){
                low++;
            }
        }
        if(low == high){
            low++;
            high--;
        }
        //左边递归
        if(left < high){
            quickSort(arr, left, high);
        }
        //右边递归
        if(right > low){
            quickSort(arr, low, right);
        }
    }
}
